package com.example.emos.wx.task;

import cn.hutool.core.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName ActiveCodeTask
 * @Description TODO
 * @Author daoketa
 * @Version 1.0
 * 生成激活码
 **/
@Component
@Scope("prototype")
public class ActiveCodeTask {
    @Autowired
    private EmailTask emailTask;

    @Autowired
    private RedisTemplate redisTemplate;

    @Async
    public void sendActiveCodeAsync(Integer userId, String email){
        String activeCode = null;
        /** 生成激活码 */
        while(true){
            activeCode = RandomUtil.randomInt(100000, 999999) + "";
            if (!redisTemplate.hasKey(activeCode)){
                break;
            }
        }
        /** 存储入 redis,有效期 1 天 */
        redisTemplate.opsForValue().set(activeCode, userId+"",1, TimeUnit.DAYS);

        /** 发送激活码到新员工邮箱 */
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject("系统新员工激活码");
        mailMessage.setText("您的新员工激活码是：" + activeCode);
        mailMessage.setTo(email);
        emailTask.sendAsync(mailMessage);
    }

}
